import axios, { AxiosResponse } from "axios";
import { message } from "antd";
interface Iuser {
  username: string;
  role: string;
  token: string;
}

// 获取缓存中的用户信息, 这是接口返回的信息。
let user: Iuser;
const getUser = () => {
  if (localStorage.getItem("userInfo")) {
    user = JSON.parse(localStorage.getItem("userInfo") as string);
  }
};
axios.defaults.baseURL = "http://localhost:3000/mock/";
// 配置请求头
axios.defaults.headers["Content-Type"] = "application/json";
// 响应时间
axios.defaults.timeout = 1000 * 0;
//请求拦截器
axios.interceptors.request.use(
  (reqConfig) => {
    getUser(); //获取用户信息
    if (user) {
      // 设置统一的请求header
      reqConfig.headers.authorization = user.token; //授权(每次请求把token带给后台)
    }
    console.log(reqConfig);
    return reqConfig;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.data.resCode !== "000000") {
      localStorage.clear(); // 清除缓存
      message.success({
        content: response.data.resMsg,
      });
    }

    return response;
  },
  (error) => {
    return Promise.resolve(error.response);
  }
);

// 处理请求返回的数据
const checkStatus = (response: AxiosResponse<any>) => {
  return new Promise((resolve, reject) => {
    if (
      response &&
      (response.status === 200 ||
        response.status === 304 ||
        response.status === 400)
    ) {
      resolve(response.data);
    } else {
      message.error({
        content: "网络异常，请检查网络连接是否正常！",
      });
    }
  });
};
const http = {
  async post(url: string, params: any) {
    const response = await axios({
      method: "post",
      url,
      data: params,
    });
    return await checkStatus(response);
  },
  async get(url: any, params: any) {
    const response = await axios({
      method: "get",
      url,
      params,
    });
    return await checkStatus(response);
  },
};

export default http;
